package org.nyt.medicalstore.controller;

import org.nyt.medicalstore.model.Inventory;
import org.nyt.medicalstore.service.InventoryService;
import org.nyt.medicalstore.dto.InventoryDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/inventories")
@CrossOrigin(origins = "*")
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;

    private InventoryDTO toDTO(Inventory inventory) {
        if (inventory == null) return null;
        InventoryDTO dto = new InventoryDTO();
        dto.setId(inventory.getId());
        dto.setDrugId(inventory.getDrug() != null ? inventory.getDrug().getId() : null);
        dto.setQuantity(inventory.getQuantity());
        dto.setMinQuantity(inventory.getMinQuantity());
        dto.setExpiryDate(inventory.getExpiryDate());
        dto.setExpiryWarningDays(inventory.getExpiryWarningDays());
        dto.setIsLowStock(inventory.getIsLowStock());
        dto.setIsExpiring(inventory.getIsExpiring());
        dto.setLastUpdated(inventory.getLastUpdated());
        return dto;
    }

    @GetMapping
    public ResponseEntity<?> getAllInventories() {
        try {
            List<Inventory> inventories = inventoryService.getAllInventories();
            List<InventoryDTO> result = inventories.stream().map(this::toDTO).collect(Collectors.toList());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取库存列表失败: " + e.getMessage() + "\"}");
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getInventory(@PathVariable Long id) {
        try {
            Inventory inventory = inventoryService.getInventoryById(id);
            if (inventory == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"库存记录不存在\"}");
            }
            InventoryDTO result = toDTO(inventory);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取库存失败: " + e.getMessage() + "\"}");
        }
    }

    @GetMapping("/low-stock")
    public ResponseEntity<?> getLowStockInventories() {
        try {
            List<Inventory> inventories = inventoryService.getLowStockDrugs();
            List<InventoryDTO> result = inventories.stream().map(this::toDTO).collect(Collectors.toList());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取库存不足列表失败: " + e.getMessage() + "\"}");
        }
    }

    @GetMapping("/expiring")
    public ResponseEntity<?> getExpiringInventories() {
        try {
            List<Inventory> inventories = inventoryService.getExpiringDrugs();
            List<InventoryDTO> result = inventories.stream().map(this::toDTO).collect(Collectors.toList());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取即将过期列表失败: " + e.getMessage() + "\"}");
        }
    }

    @PostMapping
    public ResponseEntity<?> addInventory(@RequestBody Inventory inventory) {
        try {
            Inventory savedInventory = inventoryService.saveInventory(inventory);
            InventoryDTO result = toDTO(savedInventory);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"添加库存失败: " + e.getMessage() + "\"}");
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateInventory(@PathVariable Long id, @RequestBody Inventory inventory) {
        try {
            Inventory existingInventory = inventoryService.getInventoryById(id);
            if (existingInventory == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"库存记录不存在\"}");
            }
            inventory.setId(id);
            Inventory updatedInventory = inventoryService.saveInventory(inventory);
            InventoryDTO result = toDTO(updatedInventory);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"更新库存失败: " + e.getMessage() + "\"}");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteInventory(@PathVariable Long id) {
        try {
            Inventory existingInventory = inventoryService.getInventoryById(id);
            if (existingInventory == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"库存记录不存在\"}");
            }
            inventoryService.deleteInventory(id);
            return ResponseEntity.ok("{\"message\": \"库存记录删除成功\"}");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"删除库存失败: " + e.getMessage() + "\"}");
        }
    }

    // 获取指定天数内即将过期的药品列表
    @GetMapping("/expiring/{days}")
    public List<InventoryDTO> getExpiringDrugsByDays(@PathVariable int days) {
        return inventoryService.getExpiringDrugsByDays(days).stream().map(this::toDTO).collect(Collectors.toList());
    }

    // 更新库存数量
    @PutMapping("/{id}/quantity")
    public InventoryDTO updateQuantity(@PathVariable Long id, @RequestParam Integer quantity) {
        return toDTO(inventoryService.updateQuantity(id, quantity));
    }

    // 更新最小库存预警数量
    @PutMapping("/{id}/min-quantity")
    public InventoryDTO updateMinQuantity(@PathVariable Long id, @RequestParam Integer minQuantity) {
        return toDTO(inventoryService.updateMinQuantity(id, minQuantity));
    }

    // 更新过期预警天数
    @PutMapping("/{id}/expiry-warning-days")
    public InventoryDTO updateExpiryWarningDays(@PathVariable Long id, @RequestParam Integer days) {
        return toDTO(inventoryService.updateExpiryWarningDays(id, days));
    }
}
